/*
 * @Author: byron
 * @Date: 2021-11-05 16:12:03
 * @LastEditTime: 2022-01-22 21:11:50
 */
import {
    getArticles
} from '@/api/article.js'

const state = {
    articleNum: sessionStorage.getItem('ARTICLE_NUM') != null ?
        sessionStorage.getItem('ARTICLE_NUM') : 0,
    articleList: sessionStorage.getItem('ARTICLE_LIST') != null ?
        JSON.parse(sessionStorage.getItem('ARTICLE_LIST')) : [],
    articleName: ''
}

// 同步方法
const mutations = {
    SET_ARTICLE_NUM(state, articleNum) {
        if (articleNum) {
            state.articleNum = articleNum
            sessionStorage.setItem('ARTICLE_NUM', articleNum)
        } else {
            state.articleNum = 0
            sessionStorage.removeItem('ARTICLE_NUM')
        }
    },
    SET_ARTICLE_LIST(state, article) {
        if (article) {
            const newData = state.articleList.concat(article)
            state.articleList = newData
            sessionStorage.setItem('ARTICLE_LIST', JSON.stringify(newData))
        } else {
            state.articleList = []
            sessionStorage.removeItem('ARTICLE_LIST')
        }
    },
    SET_ARTICLE_NAME(state, name) {
        if (name) {
            state.articleName = name
            sessionStorage.setItem('ARTICLE_NAME', JSON.stringify(name))
        } else {
            state.articleName = ''
            sessionStorage.removeItem('ARTICLE_NAME')
        }
    },
}

// 异步方法
// 获取文章数据方法
const actions = {
    async getArticle({
        commit,

    }, params) {
        try {
            const {
                page,
                pageSize
            } = params
            const response = await getArticles({
                'page': page,
                'pageSize': pageSize
            })
            const {
                code,
                data,
                msg
            } = response
            console.log(data.blog, 'test')
            if (code === 200) {
                const total = data.total
                commit('SET_ARTICLE_NUM', total)
                commit('SET_ARTICLE_LIST', data.blog)
                return Promise.resolve()
            } else {
                return Promise.reject(msg)
            }
        } catch (e) {
            console.log(e)
        }
    },
}

export default {
    namespaced: true,
    mutations,
    actions,
    state,
}